package cn.xgj.sfzy.controller;

import cn.xgj.sfzy.entity.User;
import cn.xgj.sfzy.service.UserService;
import cn.xgj.sfzy.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName userController
 * @Description TODO
 * @Author xgj
 * @Date 2024年10月22日 下午7:36
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User login = userService.login(user.getUserName(), user.getUserPassword());
        // 查不到
        if (login == null) {
            return Result.error("用户名或密码有误！");
        }
        //  成功
        return Result.success(login);
    }
    @Autowired
    private UserService userService;

    //查询所有
    @RequestMapping("/findAll")
    public Result findAll(User user) {
        List<User> list = userService.findAll(user);
        return Result.success(list);
    }

    //    根据id查询
    @PostMapping("/findById")
    public Result findById(Integer userId) {
        User user = userService.findById(userId);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("用户不存在");
        }
    }

    //    分页
    @RequestMapping("/findByPage")
    public Result findByPage(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "2") Integer pageSize,
            User user) {
        PageInfo<User> byPage = userService.findByPage(pageNum, pageSize, user);
        return Result.success(byPage);
    }

    //添加
    @PostMapping
    public Result add(@RequestBody User user) {
        int num = userService.add(user);
        if (num != 0) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    //修改
    @PutMapping
    public Result update(@RequestBody User user) {
        int num = userService.edit(user);
        if (num != 0) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    //删除
    @DeleteMapping("/{userId}")
    public Result delete(@PathVariable(value = "userId") Integer userId) {
        int num = userService.remove(userId);
        if (num == 0) {
            return Result.error("删除失败");
        } else if (num == -1) {
            return Result.error("该类型相关数据未删除，请删除后再试");
        } else {
            return Result.success("删除成功");
        }
    }
}
